package demo.modbus.resource;

import demo.modbus.dto.Greeting;
import demo.modbus.dto.HelloMessage;
import demo.modbus.dto.HoldingRegister;
import demo.modbus.dto.HoldingRegisterHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

/**
 * Created by leohe on 2018/6/21.
 */
@Controller
public class WebSocketResource {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketResource.class);
    @Autowired
    private HoldingRegisterHandle holdingRegisterHandle;

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    @SendToUser
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    @GetMapping("/api/HoldingRegistry")
    @ResponseBody
    public ResponseEntity getAll(){
        return new ResponseEntity(this.holdingRegisterHandle.getAll(),HttpStatus.OK);
    }

    @PostMapping("/api/HoldingRegistry")
    @ResponseBody
    public ResponseEntity updateByOffset(int offset, short value){
        return new ResponseEntity(this.holdingRegisterHandle.save(offset,new HoldingRegister(offset,"",value)), HttpStatus.OK);
    }
}
